Cascade notation in dart is a convenient way of chaining several operations on the same object, while also having access to the instance methods
and fields of the cascading object. With cascades you can write such code:
var person = Person()
..firstName = 'John'
..lastName = 'Smith'
..age = 50;
which will be the equivalent of:
var person = Person();
person.firstName = 'John';
person.lastName = 'Smith';
person.age = 50;
We can think of the cascade notation as a concise implementation of a builder pattern. Moreover, there’s a null-safe version of it ?..
that will only access members if the cascading object isn’t null
.
While such notations looks appealing it doesn’t really make sense to use for a single cascade section. For example, person..read();
seems to be an overkill. In this case usual person.read()
is much more clear. Sometimes it may also become a source of bugs. Looks at
this example:
var person = Person()..getName(); // here the instance of Person will be returned
var name = Person().getName(); // here the name will be returned
So be careful, when use cascading especially in combination with var
. And always make sure the expected value is returned.
The other side of this notation os that it might be confused with a range operator ..
from other languages (like Kotlin). So using it
without necessity will make code less readable and as a result less maintainable.